import React, { Component } from 'react';
import {
    StyleSheet,
    View,
    Text,
    Image,
    TextInput,
    TouchableOpacity,
    BackHandler,
    Platform,
} from 'react-native';

import DeviceInfo from 'react-native-device-info';
import { Formik } from 'formik';

import { RRCLoading, RRCToast } from 'react-native-overlayer';
import SplashScreen from 'react-native-splash-screen';

import { getPixel, getScreenWidth, getScreenHeight } from '../common/common';
import BaseComponent from '../component/BaseComponent';
import CheckBox from 'react-native-check-box'
import HttpUtil from '../util/HttpUtil';
import StorageUtil from '../util/StorageUtil';

import InfoImage from '../images/info.png';

import ErrorImage from '../images/error.png';

import '../component/Variables';


export default class Login extends BaseComponent {

    constructor(props) {
        super(props);
        this.state = {
            isSave: false,
            account: '',
            password: '',
            version: DeviceInfo.getVersion()
        }
        RRCToast.setToastOptions({
            toastIcons: [InfoImage, ErrorImage],
            toastBackgroundColor: 'rgba(0,0,0,0)',
            toastViewStyle: {},
            toastTextStyle: {},
            durationTime: 1000,

        })

        this.getServer();
        this.getAccountAndPassword();

    }

    async getServer() {
        let ip = await StorageUtil.get('ip');
        let port = await StorageUtil.get('port');
        let project = await StorageUtil.get('project');
        global.variables.server = ip + ':' + port + '/' + project;
    }

    async getAccountAndPassword() {
        let account = await StorageUtil.get('account');
        let password = await StorageUtil.get('password');
        let isSave = await StorageUtil.get('isSave');
        //console.log(password);

        this.setState({
            account: account,
            password: password,
            isSave: isSave,
        });
    }

    componentDidMount() {
        SplashScreen.hide();
    }

    onBackClicked = () => {
        let lastBackPressed = 0;
        if (this.props.navigation.isFocused()) {//判断   该页面是否处于聚焦状态
            if (this.lastBackPressed && this.lastBackPressed + 2000 >= Date.now()) {
                //最近2秒内按过back键，可以退出应用。
                // return false;
                BackHandler.exitApp();//直接退出APP
            } else {
                this.lastBackPressed = Date.now();
                RRCToast.show('再按一次退出应用', 2, 7000);
                return true;
            }
        }
    }


    login = async (values) => {

        // StorageUtil.save('server','1');
        let ip = await StorageUtil.get('ip');
        let port = await StorageUtil.get('port');
        let project = await StorageUtil.get('project');
        let useMode = await StorageUtil.get('useMode');
        global.variables.useMode = useMode
        if (!ip || !port || !project) {
            RRCToast.show('请设置服务及设备信息', 2, 3000);
            return;
        }

        if (!this.state.account) {
            RRCToast.show('请输入帐号', 2, 3000);
            return;
        }
        if (!this.state.password) {
            RRCToast.show('请输入密码', 2, 3000);
            return;
        }

        RRCLoading.setLoadingOptions({
            text: '请稍候',
            loadingBackgroundColor: 'rgba(0,0,0,0.0)',
            loadingViewStyle: { backgroundColor: 'rgba(0,0,0,0.8)' },
            loadingTextStyle: {}
        })

        RRCLoading.show();

        let params = {
            account: this.state.account,
            password: this.state.password,
            version: this.state.version
        }

        HttpUtil.post('user/login', params)
            .then(result => {
                if (result.httpCode == 200) {
                    if (this.state.isSave) {

                        StorageUtil.save('account', params.account);
                        StorageUtil.save('password', params.password);
                        StorageUtil.save('isSave', true);
                    } else {
                        StorageUtil.save('account', '');
                        StorageUtil.save('password', '');
                        StorageUtil.save('isSave', false);
                    }
                    RRCLoading.hide();
                    //console.log(result);
                    global.variables.authorization = result.user.id_
                    global.variables.user = result.user;
                    this.props.navigation.navigate('Main');
                } else if (result.httpCode == 303) {
                    RRCLoading.hide();
                    RRCToast.show(result.msg ? result.msg : '用户名或密码错误', 2, 7000);
                } else {
                    RRCLoading.hide();
                    RRCToast.show(result.msg ? result.msg : '系统异常', 1, 7000);
                }
            })
            .catch(error => {
                RRCLoading.hide();
                RRCToast.show('系统异常', 1, 7000);
            })
    }

    ipSetting = () => {
        this.props.navigation.navigate('IpSetting');
    }

    handleChange = (field) => {
        this.setState(field);
    }

    render() {

        return (
            <View style={styles.container}>
                <View style={{ height: getScreenHeight() }}>
                    <View style={styles.systemBox}>
                        <Text style={styles.system}>
                            资源资产电子化平台
                        </Text>
                        <View style={styles.buleLine}></View>
                    </View>
                    <Formik
                        initialValues={{ account: this.state.account, password: this.state.passord }}
                        onSubmit={values => this.login(values)}
                    >
                        {({ handleChange, handleBlur, handleSubmit, values }) => (
                            <View style={styles.userBox}>
                                <View style={styles.user}>
                                    <View style={{ justifyContent: 'center' }}>
                                        <Image source={require('../images/user.png')} style={styles.userAccontIcon} />
                                    </View>
                                    <View style={{ justifyContent: 'center' }}>
                                        <TextInput onChangeText={text => this.handleChange({ account: text })} value={this.state.account} style={styles.userAccontInput} placeholder="账号" />
                                    </View>
                                </View>
                                <View style={styles.user}>
                                    <View style={{ justifyContent: 'center' }}>
                                        <Image source={require('../images/pwd.png')} style={styles.userAccontIcon} />
                                    </View>
                                    <View style={{ justifyContent: 'center' }}>
                                        <TextInput onChangeText={text => this.handleChange({ password: text })} value={this.state.password} style={styles.userAccontInput} secureTextEntry={true} placeholder="密码" />
                                    </View>
                                </View>
                                <View style={{ height: getPixel(30), paddingLeft: getPixel(5), flexDirection: 'row' }}>
                                    <CheckBox
                                        style={{ width: getPixel(20), height: getPixel(40), paddingTop: getPixel(10) }}
                                        unCheckedImage={<Image source={require('../images/unchecked.png')} style={{ resizeMode: 'contain', width: getPixel(20), height: getPixel(20), }} />}
                                        checkedImage={<Image source={require('../images/checked.png')} style={{ resizeMode: 'contain', width: getPixel(20), height: getPixel(20), }} />}
                                        onClick={() => {
                                            this.setState({
                                                isSave: !this.state.isSave,
                                            })
                                        }}
                                        isChecked={this.state.isSave}
                                        rightTextStyle={{ color: '#999' }}
                                    />
                                    <Text style={{ height: getPixel(40), lineHeight: getPixel(40), marginLeft: getPixel(10) }}>记住用户密码</Text>
                                </View>

                                <View style={{ marginTop: getPixel(10), alignItems: 'flex-end' }}>
                                    <TouchableOpacity onPress={this.ipSetting}>
                                        <Text style={styles.ipSetting}>设置</Text>
                                    </TouchableOpacity>
                                </View>

                                <View style={{ marginTop: getPixel(20) }}>
                                    <TouchableOpacity onPress={handleSubmit}>
                                        <View style={{ backgroundColor: '#4a69dd', height: getPixel(40), borderRadius: getPixel(19) }}>
                                            <Text style={{ color: '#FFFFFF', textAlign: 'center', fontSize: getPixel(16), lineHeight: getPixel(40) }}>在线登录</Text>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                                {/* <View style={{marginTop: getPixel(15)}}>
                                <TouchableOpacity activeOpacity={0.2} focusedOpacity={0.5}>
                                    <View style={{ backgroundColor: '#ecf0ff', height: getPixel(40), borderRadius: getPixel(19), borderStyle: 'dashed', borderWidth: 1, borderColor: '#5986ff' }}>
                                        <Text style={{ color: '#4A69DD', textAlign: 'center', fontSize: getPixel(16), lineHeight: getPixel(40) }}>离线登录</Text>
                                    </View>
                                </TouchableOpacity>
                            </View> */}
                            </View>
                        )}
                    </Formik>
                    <View style={{ position: 'absolute', bottom: 0, marginBottom: getPixel(40), marginLeft: getScreenWidth() / 2 - getPixel(75), alignItems: 'center' }}>
                        <View>
                            <Text style={{ color: '#999999', fontSize: getPixel(14) }}>版本：V{this.state.version}</Text>
                        </View>
                        <View style={{ marginTop: getPixel(10) }}>
                            <Text style={{ color: '#999999', fontSize: getPixel(14) }}>沃科合众技术支持</Text>
                        </View>
                    </View>
                </View>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginLeft: getPixel(20),
        marginRight: getPixel(20),
        alignItems: 'center',
    },

    systemBox: {
        paddingTop: getPixel(100),
    },

    system: {
        fontSize: getPixel(24),
        color: '#4A69DD',
        textAlign: 'center',
        fontWeight: 'bold',
        marginBottom: getPixel(15)
    },

    buleLine: {
        width: getPixel(40),
        height: getPixel(6),
        backgroundColor: '#4A69DD',
        marginLeft: getScreenWidth() / 2 - getPixel(40),
        borderRadius: 5,
    },

    userBox: {
        paddingTop: getPixel(50),
    },

    user: {
        flexDirection: 'row',
        borderStyle: 'solid',
        borderBottomColor: '#D3D3D3',
        borderBottomWidth: 1,
        height: getPixel(50),
    },

    userAccontIcon: {
        resizeMode: 'contain',
        width: getPixel(30),
        height: getPixel(30),

    },

    userAccontInput: {
        width: getScreenWidth() - 70,
        height: getPixel(40),
        fontSize: getPixel(15),
        paddingLeft: getPixel(10),
        paddingVertical: 0,
    },

    ipSetting: {
        fontSize: getPixel(15),
        textAlign: 'right',
        color: '#4A69DD',
        textDecorationLine: 'underline',
        width: getPixel(50),
    },
});